import pymongo
import paramiko
from sshtunnel import SSHTunnelForwarder

# SSH 服务器信息
ssh_host = '47.100.211.213'  # 阿里云服务器的公网 IP
ssh_port = 22
ssh_username = 'root'
ssh_private_key_path = '/Users/ra1chi/pythonscripts/workflow/data/盯潮测试服.pem'  # 私钥文件的路径

# MongoDB 实例信息
mongo_host = 'dds-uf67b0329a2101741.mongodb.rds.aliyuncs.com'  # MongoDB 在阿里云服务器上的地址
mongo_port = 3717
mongo_username = 'root'
mongo_password = 'Dingstock123'
mongo_database = 'kream-bid'

# 建立 SSH 隧道
server = SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_username,
    ssh_pkey=paramiko.RSAKey.from_private_key_file(ssh_private_key_path),
    remote_bind_address=(mongo_host, mongo_port)
)

# 启动 SSH 隧道
server.start()

# 连接到 MongoDB
local_port = server.local_bind_port
client = pymongo.MongoClient(f'mongodb://{mongo_username}:{mongo_password}@localhost:{local_port}/{mongo_database}')

# 选择数据库和集合
db = client[mongo_database]
collection = db['accounts']

# 示例操作：插入一条文档
result = [i for i in collection.find({})]
print(f"Inserted document with ID: {result}")

# 关闭 MongoDB 连接
client.close()

# 停止 SSH 隧道
server.stop()